package com.szbber.door.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import com.szbber.door.view.LoadingDialog

abstract class BaseFragment: Fragment() {

    private var contentView: View? = null
    private var mIsVisible = false // fragment是否显示了
    private val isPrepared = false
    private val isFirst = true //只加载一次界面

    private var loadingDialog: LoadingDialog? = null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        state: Bundle?
    ): View? {
        contentView = inflater.inflate(this@BaseFragment.getLayoutResId(), container, false)
        this@BaseFragment.initView(arguments)
        this@BaseFragment.attachView()
        return contentView
    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        if (userVisibleHint) { //fragment可见
            mIsVisible = true
            onVisible()
        } else { //fragment不可见
            mIsVisible = false
            attachView()
        }
    }

    protected open fun onVisible() {
        if (isFirst) {
            attachView()
        }
        loadBaseData() //根据获取的数据来调用showView()切换界面
    }

    open fun loadBaseData() {
        if (!mIsVisible || !isPrepared || !isFirst) {
            return
        }
    }

    open fun showLoadingDialog() {
        dismissLoadingDialog()
        val builder: LoadingDialog.Builder =
            LoadingDialog.Builder(activity)
                .setMessage("加载中...")
                .setCancelable(true)
        loadingDialog = builder.create()
        loadingDialog?.show()
    }

    open fun dismissLoadingDialog() {
        if (null != loadingDialog && loadingDialog!!.isShowing) {
            loadingDialog?.dismiss()
            loadingDialog = null
        }
    }


    abstract fun getLayoutResId(): Int

    abstract fun attachView()

    protected open fun initView(bundle: Bundle?) {}

    open fun getSupportActivity(): FragmentActivity? {
        return super.getActivity()
    }

    open fun getContentView(): View? {
        return contentView
    }

}